//
//  BVMyCollectionViewController.m
//  BuyVegetables1
//
//  Created by 于善昌 on 16/8/22.
//  Copyright © 2016年 YSC. All rights reserved.
//

#import "BVMyCollectionViewController.h"
#import "BVConst.h"
#import "HttpTool.h"
#import "BVShopCart.h"
#import "MBProgressHUD+MJ.h"
#import "BVMyCollectionCell.h"
#import "BVShopsLeftCategoryDetail.h"

#define MYCOLLECTIONIDENTIFIER @"MyCollectionIdentifier"
#define NIBNAME @"BVMyCollectionCell"

@interface BVMyCollectionViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableViews;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic) BOOL isEditing;

@end

@implementation BVMyCollectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"我的收藏";

    [self setNav];
}

- (void)setNav{
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"edit_btn"] style:UIBarButtonItemStyleDone target:self action:@selector(editBtnClick)];
}
#pragma 编辑按钮点击事件
- (void)editBtnClick{
    _isEditing = !_isEditing;
    [self.tableViews setEditing:_isEditing animated:YES];
    
    if (_isEditing) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeBtnClick)];
    }else{
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"edit_btn"] style:UIBarButtonItemStyleDone target:self action:@selector(editBtnClick)];
    }
}
- (void)closeBtnClick{
    [self.tableViews setEditing:!_isEditing animated:YES];
    _isEditing = NO;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"edit_btn"] style:UIBarButtonItemStyleDone target:self action:@selector(editBtnClick)];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadMyCollectionData];
}
- (UITableView *)tableViews{
    if (!_tableViews) {
        _tableViews = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, BVScreenW, BVScreenH - 64) style:UITableViewStyleGrouped];
        _tableViews.delegate = self;
        _tableViews.dataSource = self;
        [self.tableViews registerNib:[UINib nibWithNibName:NIBNAME bundle:nil] forCellReuseIdentifier:MYCOLLECTIONIDENTIFIER];
        _tableViews.tableFooterView = [[UIView alloc] init];
        [self.view addSubview:_tableViews];
    }
    return _tableViews;
}
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
#pragma 获取我的收藏列表
- (void)loadMyCollectionData{
    
    NSString *url = [NSString stringWithFormat:@"%@/VegetableUserAPI/getCollectByUser",Path];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary * userinfo =[defaults objectForKey:@"USERINFO"];
    NSString *user_id = userinfo[@"id"];
    params[@"user_id"] = user_id;
    SHOWLOADING
    [HttpTool get:url params:params success:^(id responseObj) {
            HIDELOADING
            if ([responseObj[@"code"] isEqualToString:@"0"]) {
                for (NSDictionary *collecDict in responseObj[@"data"]) {
                    BVShopsLeftCategoryDetail *collecShopsDetailModel = [[BVShopsLeftCategoryDetail alloc] initWithDict:collecDict];
                    [self.dataSource addObject:collecShopsDetailModel];
                }
                [self.tableViews reloadData];
            } else {
                ERROR(@"没有收藏信息!");
            }
        } failure:^(NSError *error) {
            NETWORKINGERROR
        }];
}

#pragma 购物车点击事件
-(void)goShoppingBtnClick:(UIButton * )button{
    
    BVShopsLeftCategoryDetail *collecShopsDetailModel = self.dataSource[button.tag - 1000];
//    NSLog(@"收藏商品ID是：%@",collecShopsDetailModel.ID);
    if ([BVShopCart lookUpShop:collecShopsDetailModel] != nil) {
        ERROR(@"已在购物车!");
    } else {
        SUCCESS(@"添加成功!");
        // 添加商品到数据库
        [BVShopCart addShopToCart:collecShopsDetailModel];
    }
}

#pragma mark --
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 110;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BVMyCollectionCell *collecCell = [tableView dequeueReusableCellWithIdentifier:MYCOLLECTIONIDENTIFIER];
    collecCell.selectionStyle = UITableViewCellSelectionStyleNone;
    BVShopsLeftCategoryDetail *collecShopsDetailModel = self.dataSource[indexPath.section];
    [collecCell addDataWithModel:collecShopsDetailModel];
    
    [collecCell.goShoppingBtn addTarget:self action:@selector(goShoppingBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    collecCell.goShoppingBtn.tag = indexPath.section + 1000;
    return collecCell;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewRowAction *delete = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        BVShopsLeftCategoryDetail *collecShopsDetailModel = self.dataSource[indexPath.section];
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        NSString *url = [NSString stringWithFormat:@"%@/VegetableUserAPI/deleteCollect", Path];
        NSDictionary * userinfo =[[NSUserDefaults standardUserDefaults] objectForKey:@"USERINFO"];
        
        params[@"user_id"] = userinfo[@"id"];
        params[@"goods_id"] = collecShopsDetailModel.ID;
        [HttpTool get:url params:params success:^(id responseObj) {
            if ([responseObj[@"code"] isEqualToString:@"0"]) {
                [self.dataSource removeObjectAtIndex:indexPath.section];
                [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationBottom];
            }
        } failure:^(NSError *error) {
            ERROR(@"删除失败");
        }];
    }];
    return @[delete];
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    return @"";
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001f;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.dataSource removeObjectAtIndex:indexPath.section];
    [self.tableViews deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationBottom];;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
